package pro.shuangxi.model.downfile.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import mybatisplus.pojo.DownFileTask;
import mybatisplus.pojo.DownFileTaskLink;
import mybatisplus.service.IDownFileTaskLinkService;
import mybatisplus.service.IDownFileTaskService;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import pro.shuangxi.common.utils.WebPageUtils;
import pro.shuangxi.common.vo.PageVo;
import pro.shuangxi.common.vo.Result;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author mengshx
 * @since 2022-06-25
 */
@RestController
@RequestMapping("/downFileTask")
public class DownFileTaskController {
    @Autowired
    IDownFileTaskService downFileTaskService;
    @Autowired
    IDownFileTaskLinkService downFileTaskLinkService;

    @RequestMapping("page.do")
    public Result page(PageVo pageVo) throws Exception{
        Page page = downFileTaskService.page(pageVo.getLayuiPage());
        return Result.OK(page);
        }
    @RequestMapping("add.do")
    public Result add(@RequestBody DownFileTask task) throws Exception{
        downFileTaskService.save(task);
        Document document = Jsoup.connect(task.getTargetUrl()).get();
        Elements title = document.getElementsByTag("title");
        task.setTargetName(title.text());
        analysis(task.getTargetUrl(), String.valueOf(task.getId()));
        return Result.OK("ok");
        }
    @RequestMapping("reAnalysis.do")
    public Result reAnalysis(String id) throws Exception{
        DownFileTask task = downFileTaskService.getById(id);
        try {
            analysis(task.getTargetUrl(), id);
        } catch (Exception e) {
            return Result.ERR("你确定路径没问题？？？");
        }
        return Result.OK("ok");
        }
    public void analysis(String url,String taskId) throws Exception{
        List<String> link = WebPageUtils.analysisLink(url);
        downFileTaskLinkService.remove(new QueryWrapper<DownFileTaskLink>().eq("task_id", taskId));
        List<DownFileTaskLink> collect = link.stream().map(item -> {
            DownFileTaskLink taskLink = new DownFileTaskLink();
            taskLink.setTaskId(Integer.parseInt(taskId));
            taskLink.setTaskLink(item);
            return taskLink;
        }).collect(Collectors.toList());
        downFileTaskLinkService.saveBatch(collect);
        }


}
